<template>
	<div v-if="getShow">
		<h2 class="login-title">欢迎使用GpuMall</h2>
		<div class="login-type">
			<div @click="chanageLoginType(2)" :class="{ 'activeType': loginType == 2 }">密码登录</div>
			<div @click="chanageLoginType(1)" :class="{ 'activeType': loginType == 1 }">短信登录</div>
			
		</div>
		<a-form loading :model="state.formState" name="normal_login" class="login-form" @finish="onFinish">
			<a-form-item name="phone" :rules="[{ required: true, message: '请输入用户名!' }]">
				<a-input v-model:value="state.formState.phone" allowClear autocomplete="off" size="large"
					placeholder="请输入手机号">
					<template #prefix>
						<svg-icon name="icon_account_a" style="width: 12px;height: 12px;" />
					</template>
				</a-input>
			</a-form-item>

			<a-form-item v-if="loginType == 1" name="code" :rules="[{ required: true, message: '请输入验证码!' }]">
				<div class="form-item-code">
					<a-input v-model:value="state.formState.code" allowClear autocomplete="off" size="large"
						placeholder="验证码">
						<template #prefix>
							<svg-icon name="icon_verify" style="width: 12px;height: 12px;" />
						</template>
					</a-input>
					<a-button type="link" :disabled="count != 0" class="get-code-btn" @click="sendCode()">{{ count > 0 ?
						count : '获取验证码' }} </a-button>
				</div>
			</a-form-item>

			<a-form-item v-if="loginType == 2" name="password" :rules="[{ required: true, message: '请输入密码!' }]">
				<a-input-password v-model:value="state.formState.password" autocomplete="off" placeholder="请输入密码"
					size="large">
					<template #prefix>
						<svg-icon name="icon_lock" style="width: 12px;height: 12px;" />
					</template>
				</a-input-password>
			</a-form-item>

			<!-- geetest验证 -->
			<div id="captcha" style="height: 0;">
				<GeetestCaptcha :captcha-config="state.captchaConfig" />
			</div>
			<a-form-item>
				<a-button type="primary" style="width: 100%" html-type="submit" size="large" class="login-form-button">
					登录
				</a-button>
			</a-form-item>

			<div class="login-opts">
				<div>没有账号，<span class="opt" @click="setLoginState('register')">立即注册</span></div>
				<span class="opt" v-if="loginType == 2" @click="findPwd">忘记密码</span>
				<span>登录注册即表示同意<span @click="goDocsAgreement" class="opt" v-if="loginType == 1">《用户协议》</span><span class="opt" @click="goDocsPrivacy">《隐私政策》</span></span>
			</div>
		</a-form>
	</div>
</template>

<script setup>
// 密码登录需要验证码，短信登录需要在发送短信的时候调用验证码
import { reactive, ref, computed, onMounted } from 'vue'
import { useAuthStore } from 'stores/auth.js'
import { useLoginState } from '@/hooks/sys/useLogin.js'
import { useCountDown } from "@/hooks/sys/useCountDown.js";
import GeetestCaptcha from "./GeetestCaptcha.vue";
import { XsyMessage } from '@/libs/util.toast'
import { isvalidPhone } from '@/libs/util.valid.js'
import { useRouter } from 'vue-router'
import { authGetCode } from 'api/modules/api.auth'

const emit = defineEmits(['findPwd']);

const router = useRouter()
const { count, countDown } = useCountDown();

const authStore = useAuthStore()
const { setLoginState, getLoginState } = useLoginState()
const getShow = computed(() => {
	return getLoginState.value === 'login'
})

const state = reactive({
	formState: {},
	captchaConfig: {
		config: {
			captchaId: "e0ff0f201c666d314840dfd88a2316f8",
			language: "zho",
			product: "bind",
		},
		handler: captchaHandler,
	},
})

// 登录方式：1账号登录，2短信登录
const loginType = ref(2)

function chanageLoginType(key) {
	loginType.value = key
}

const onFinish = values => {
	// 密码验证
	if (loginType.value == 2) {
		if (window.captchaObj) {
			window.captchaObj.showCaptcha();
		} else {
			alert("请等待验证初始化完成");
			return false;
		}
	} else {
		const params = {
			loginBy: 'code',
			phone: state.formState.phone,
			password: state.formState.password || undefined,
			code: state.formState.code || undefined,
		}

		authStore.login(params).then(res => {
			XsyMessage.success(`欢迎: ${res.data.user.nickname}`)
			router.push('/personalSpace')
		}).catch(() => {

		})

	}
}

// 点击发送验证码
function sendCode() {
	if (isvalidPhone(state.formState.phone)) {
		if (window.captchaObj) {
			window.captchaObj.showCaptcha();
		} else {
			alert("请等待验证初始化完成");
			return false;
		}
	} else {
		XsyMessage.warning('请输入正确手机号');
	}
}

// 调用发送验证码接口
const getCode = () => {
	const params = {
		scene: 'login',
		account: state.formState.phone,
		type: 'phone',
		...GeetestResult.value
	}

	authGetCode(params).then(res => {
		(res.code == 0) && XsyMessage.success('发送成功')
	})
};

function captchaHandler(captchaObj) {
	window.captchaObj = captchaObj;
	captchaObj
		.appendTo("#captcha")
		.onReady(function () {
			
		})
		.onNextReady(function () {
			
		})
		.onBoxShow(function () {
		
		})
		.onError(function (e) {
		
		})
		.onSuccess(function () {
			if (state.captchaConfig.config.product === "bind") {
				validate();
			}
		});
}

// 完成验证
const GeetestResult = ref()
function validate() {
	var result = window.captchaObj.getValidate();
	GeetestResult.value = result
	if (!result) {
		alert("请先完成验证！");
		return;
	}

	// 密码验证
	if (loginType.value == 2) {
		const params = {
			loginBy: 'pwd',
			phone: state.formState.phone,
			password: state.formState.password || undefined,
			code: state.formState.code || undefined,
			...result
		}

		authStore.login(params).then(res => {
			XsyMessage.success(`欢迎: ${res.data.user.nickname}`)
			router.push('/personalSpace')
		}).catch(() => {

		})
	} else {
		countDown(60, getCode)
	}

}

// 找回密码
const findPwd = () => {
	emit('findPwd')
}

// 打开用户协议
function goDocsAgreement() {
    window.open(window.location.origin + '/docs/help_document/user_agreement/agreement', '_blank')
}

// 打开隐私协议
function goDocsPrivacy() {
    window.open(window.location.origin + '/docs/help_document/user_agreement/privacy', '_blank')
}


onMounted(() => {
	let html = document.documentElement;
	html.style.fontSize = 100 * (html.clientWidth / 1440) + "px";
	// 监听 window 的 resize 事件．在浏览器窗口变化时再设置下区域高度．
	window.onresize = () => {
		let html = document.documentElement;
		html.style.fontSize = 100 * (html.clientWidth / 1440) + "px";
	};
})

</script>

<style lang="scss" scoped>
.login-title {
	margin-bottom: 0.64rem;
	color: #222;
	font-family: PingFang SC;
	font-size: 0.4rem;
	font-style: normal;
	font-weight: 600;
	line-height: normal;
}

.login-type {
	display: flex;
	margin-bottom: 0.24rem;

	&>div {
		color: #223354;
		font-family: PingFang SC;
		font-size: 0.16rem;
		font-style: normal;
		font-weight: 500;
		line-height: normal;
		margin-right: 0.24rem;
		cursor: pointer;
	}

	.activeType {
		color: #07F;
	}

	.activeType::after {
		height: 2px;
		content: '';
		background: #07F;
		display: block;
		margin-top: 4px;
	}
}

.login-form {
	overflow: hidden;

	.login-opts {
		display: flex;
		justify-content: space-between;
		color: #333;
		font-family: PingFang SC;
		font-size: 0.12rem;
		font-style: normal;
		font-weight: 500;
		line-height: normal;

		.opt {
			color: #07F;
		}
	}

	.ant-input-affix-wrapper {
		border-radius: 8px;
	}

	.login-code {
		cursor: pointer;
	}
}

.form-item-code {
	position: relative;
	border-radius: 6px;

	.get-code-btn {
		position: absolute;
		right: 0;
		height: 100%;
		border-radius: 0px 4px 4px 0px;
		background: #F2F8FF;
		z-index: 100;
		box-sizing: border-box;
		border: 1px solid #d9d9d9;
		border-left: none;
	}
}
</style>
